<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\notice;

use app\enum\NoticeEnum;
use app\model\mysql\NoticeModel;
use app\service\BaseService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

final class NoticeProducerService extends BaseService
{
    /**
     * @var int 最大长度
     */
    private const MAX_LENGTH = 200;

    /**
     * @var mixed|string 缓存key
     */
    private $redisKey;

    public function __construct()
    {
        $this->redisKey = NoticeEnum::NOTICE_LIST_KEY;
    }

    /**
     * 获取待执行列表.
     * @param int $page 当前页
     * @param int $limit 分页
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getWaitList(int $page = 1, int $limit = 200)
    {
        $redis = Cache::store('redis')->handler();
        if ($redis->hLen($this->redisKey) > self::MAX_LENGTH) {
            return [];
        }
        return (new NoticeModel())
            ->where('status', NoticeModel::STATUS_WAIT)
            ->limit(($page - 1) * $limit, $limit)
            ->select();
    }

    /**
     * 执行任务
     * @return true
     */
    public function runTask(NoticeModel $model): bool
    {
        $redis = Cache::store('redis')->handler();
        $value = json_encode([
            'id' => $model->getKey(),
            'type' => $model->getAttr('type'),
            'date' => $model->getAttr('date'),
        ]);
        $field = md5($value);
        if (! $redis->hExists($this->redisKey, $field)) {
            $redis->hSetnx($this->redisKey, $field, $value);
        }
        return true;
    }
}
